// 控制管理js
$(function () {
    // 初始化
    // 公共部分
    const form = layui.form;
    const table = layui.table;
    // 用户类型，用户级别列表（用于展示，索引为value，值为label）
    let userType = []
    let userLevel = []
    // 规则类型数组(表格展示的时候把数字转成对应类型)
    const ruleType = ['全部产品', '数据产品', '服务产品']
    //0表示新增 其他值表示修改 其他值是id
    let priceAddOrEdit = 0;
    //0表示新增 其他值表示修改 其他值是id
    let visibleAddOrEdit = 0;
    // 可见控制部分
    // 选中的指定用户数据
    let speUsers = []
    // 价格部分
    // 选中的指定用户数据
    let priceSpeUsers = []
    // 请求用户级别，用户类型
    $(function () {
        $.ajax({
            timeout: 30000,
            url: window.Http + "/system/dict/data/getDictList",
            type: 'GET',
            headers: {
                'Authorization': "Bearer " + sessionStorage.getItem('Token')
            },
            data: {
                dictType: 'user_level'
            },
            success: function (res) {
                if (res.code === 200) {
                    priceUserLevelCas.setOptions(dataFormat(res.data, 'dictValue', 'dictLabel'))
                    visibleUserLevelCas.setOptions(dataFormat(res.data, 'dictValue', 'dictLabel'))
                    res.data.forEach((item) => {
                        userLevel[Number(item.dictValue)] = item.dictLabel;
                    })
                }
            }
        })
        $.ajax({
            timeout: 30000,
            url: window.Http + "/system/dict/data/getDictList",
            type: 'GET',
            headers: {
                'Authorization': "Bearer " + sessionStorage.getItem('Token')
            },
            data: {
                dictType: 'user_type'
            },
            success: function (res) {
                if (res.code === 200) {
                    // console.log('res.data', res.data[0].dictValue,typeof  res.data[0].dictValue)
                    priceUserTypeCas.setOptions(dataFormat(res.data, 'dictValue', 'dictLabel'))
                    visibleUserTypeCas.setOptions(dataFormat(res.data, 'dictValue', 'dictLabel'))
                    res.data.forEach((item) => {
                        userType[item.dictValue] = item.dictLabel;
                    })
                }
            }
        })
    })

    // 可见控制
    // 可见用户级别下拉框
    let visibleUserLevelCas = layui.layCascader({
        elem: `#visibleUserLevel`,
        clearable: true, // 显示清除按钮
        // options:data,
        props: {
            multiple: false, // 允许多选
            // strictMode:true//开启严格模式
        },
    })
    visibleUserLevelCas.changeEvent(function (value, node) {
        console.log('级别的变化', value)
    })
    // 可见用户类型下拉框
    let visibleUserTypeCas = layui.layCascader({
        elem: `#visibleUserType`,
        clearable: true, // 显示清除按钮
        // options:data,
        props: {
            multiple: true, // 允许多选
            // strictMode:true//开启严格模式
        },
        // value:selectedData
    })
    visibleUserTypeCas.changeEvent(function (value, node) {
        console.log('类型的变化：', value, node)
    })
    // 可见用户指定下拉框
    let visibleSpeUserCas = layui.layCascader({//单选
        elem: `#visibleSpeUser`,
        clearable: true, // 显示清除按钮
        props: {
            multiple: true, // 允许多选
            // strictMode:true//开启严格模式
        },
    })
    visibleSpeUserCas.changeEvent(function (value, node) {
        console.log('用户变化', value, typeof value)
    })
    // 可见表格实例
    const visibleRuleTable = table.render({
        elem: '#visibleRuleTable'
        , height: '.layui-tab-item'
        , data: []
        , page: true //开启分页
        , cols: [[ //表头
            { title: '序号', type: "numbers", width: 60 }
            , { field: 'systemControlName', title: '规则名称', width: 150 }
            , {
                field: 'isVisible', title: '可见性', width: 80, templet: function (d) {
                    if (d.isVisible == 1) {
                        return `<span>可见</span>`
                    } else {
                        return `<span>不可见</span>`
                    }
                }
            }
            , {
                field: 'speUserList', title: '指定用户', templet: function (d) {
                    if (d.speUserList && d.speUserList.length > 0) {
                        const speUserNameList = d.speUserList.map(item => item.speUserName).join(',')
                        return `<span>${speUserNameList}</span>`
                    } else {
                        return `<span>暂无</span>`
                    }
                }
            }
            , {
                field: 'speUserTypeList', title: '用户类型', templet: function (d) {
                    // console.log('userType', userType ,userType[0],userType.length)
                    // console.log('speUserTypeList', d.speUserTypeList,d.speUserTypeList.length)
                    if (userType && userType.length > 0 && d.speUserTypeList && d.speUserTypeList.length) {
                        const speUserTypeNameList = d.speUserTypeList.map(item => userType[item]).join(',');
                        return `<span>${speUserTypeNameList}</span>`
                    }
                    else {
                        return `<span>暂无</span>`
                    }
                }
            }
            , {
                field: 'userLevel', title: '用户级别', templet: function (d) {
                    if (userLevel && userLevel.length > 0 && d.userLevel) {
                        const userLevelName = userLevel[d.userLevel];
                        return `<span>${userLevelName}</span>`
                    } else {
                        return `<span>暂无</span>`
                    }
                }
            }
            , { field: 'remark', title: '备注', }
            , { title: '操作', toolbar: '#barRule', width: 200 },
        ]]
    })

    // 事件处理
    // 可见表格相关操作-编辑，查看详情，删除
    layui.table.on('tool(visibleRuleTableFilter)', function (obj) {
        const data = obj.data;
        console.log('data', data)
        if (obj.event === 'edit') {
            const formPosition = $(".visibleRule").offset().top;
            // 减少滚动距离，例如减少100像素
            const scrollPosition = formPosition - 100;
            // 使用animate方法滚动到表单元素的位置
            $("html, body").animate({
                scrollTop: scrollPosition
            }, 1000); // 1000表示滚动动画的持续时间（以毫秒为单位）
            // 取消禁用
            $("input").attr("disabled", false);
            $("input").css("background-color", '#fff');
            $('.visibleSubmitOperate').css('display', 'flex')
            visibleFormValue(data)
            if (data.id === 0) {
                console.log('addOrEdit标识错误')
            }
            visibleAddOrEdit = data.id;
            console.log('visibleAddOrEdit', visibleAddOrEdit)
        } else if (obj.event === 'detail') {
            const formPosition = $(".visibleRule").offset().top;
            // 减少滚动距离，例如减少100像素
            const scrollPosition = formPosition - 100;
            // 使用animate方法滚动到表单元素的位置
            $("html, body").animate({
                scrollTop: scrollPosition
            }, 1000); // 1000表示滚动动画的持续时间（以毫秒为单位）
            visibleFormValue(data)
            // 禁用表单
            $("input").attr("disabled", true);
            $("input").css("background-color", '#e9ecef');
        } else if (obj.event === 'delete') {
            const id = obj.data.id;
            $.ajax({
                timeout: 30000,
                url: window.Http + "/system/control/del/" + id,
                type: 'DELETE',
                headers: {
                    'Authorization': "Bearer " + sessionStorage.getItem('Token')
                },
                success: function (res) {
                    if (res.code === 200) {
                        layer.msg('删除成功')
                        visibleRuleReq()
                    } else {
                        layer.msg(res.msg)
                    }
                }
            })
        }
    })
    // 提交按钮 可见规则
    $('.submitVisibleRule').on('click', function () {

        const visibleRuleName = form.val('visibleNameForm')
        const visibleRule = { ...visibleRuleName }
        const visibleForm = form.val('visibleForm')
        visibleRule.single = JSON.stringify([
            { type: 'userLevel', method: visibleForm.userLevelMethod, value: visibleForm.userLevelValue }
        ])
        visibleRule.collection = JSON.stringify([
            {
                class: 'userType',
                set: priceUserTypeCas.getCheckedValues()
            }, {
                class: "speUser",
                set: priceSpeUserCas.getCheckedValues()
            }])
        visibleRule.isVisible = visibleForm.isVisible;
        visibleRule.ruleMode = visibleForm.mode;
        visibleRule.speUserIdList = visibleSpeUserCas.getCheckedValues()
        visibleRule.speUserTypeList = visibleUserTypeCas.getCheckedValues();
        visibleRule.userLevel = visibleForm.userLevelValue;
        console.log('visibleRule', visibleRule)
        if (visibleAddOrEdit === 0) {
            $.ajax({
                timeout: 30000,
                url: window.Http + "/system/control/create",
                type: 'POST',
                headers: {
                    'Authorization': "Bearer " + sessionStorage.getItem('Token')
                },
                contentType: 'application/json',
                data: JSON.stringify(visibleRule),
                success: function (res) {
                    if (res.code === 200) {
                        layer.msg('新增成功')
                        visibleRuleReq()
                        $('.visibleSubmitOperate').css('display', 'none')
                        visibleFormValue()
                        form.val('userForm', {
                            searchUserName: null
                        })
                    } else {
                        layer.msg(res.msg)
                    }
                }
            })
        } else {
            visibleRule.id = visibleAddOrEdit
            $.ajax({
                timeout: 30000,
                url: window.Http + "/system/control/update",
                type: 'PUT',
                headers: {
                    'Authorization': "Bearer " + sessionStorage.getItem('Token')
                },
                contentType: 'application/json',
                data: JSON.stringify(visibleRule),
                success: function (res) {
                    if (res.code === 200) {
                        layer.msg('修改成功')
                        visibleAddOrEdit = 0
                        $('.visibleSubmitOperate').css('display', 'none')
                        visibleFormValue()
                        form.val('userForm', {
                            searchUserName: null
                        })
                        visibleRuleReq()
                    } else {
                        layer.msg(res.msg)
                    }
                }
            })
        }
    })
    // 可见 根据关键字搜索规则 按钮
    $('.visibleSearchBtn').on('click', function () {
        // 使用 jQuery 选择器选择输入框并获取其值
        const inputValue = $(".visibleSearch input[name='keyword']").val();
        // 输出输入框的值
        console.log(inputValue);
        visibleRuleReq(inputValue);
    })
    // 指定用户搜索功能
    $('.searchUser').on('click', '.visibleUserSearch', function () {
        const userName = form.val('visibleForm').searchUserName;
        console.log('userName', userName)
        // 使用示例
        userSearchReq(userName, speUsers)
            .then(function (result) {
                // 处理成功结果
                console.log(result);
                const { userArr, selectedData } = result;
                visibleSpeUserCasRender(userArr, selectedData)
            })

    })
    // 新增可见规则
    $('#addVisibleBtn').on('click', function () {
        // 清空表单
        form.val('userForm', {
            searchUserName: null
        })
        visibleFormValue()
        // 取消禁用
        $("input").attr("disabled", false);
        $("input").css("background-color", '#fff');
        // layer.open(rulePop)
        const formPosition = $(".visibleRule").offset().top;
        // 减少滚动距离，例如减少100像素
        const scrollPosition = formPosition - 100;
        // 使用animate方法滚动到表单元素的位置
        $("html, body").animate({
            scrollTop: scrollPosition
        }, 100); // 1000表示滚动动画的持续时间（以毫秒为单位）
        $('.visibleSubmitOperate').css('display', 'flex')

    })

    /******************申购规则******************/
    // 用户类型和用户级别，指定用户级联选择器对象
    let priceUserLevelCas = layui.layCascader({
        elem: `#userLevel`,
        clearable: true, // 显示清除按钮
        // options:data,
        props: {
            multiple: false, // 允许多选
            // strictMode:true//开启严格模式
        },
    })
    priceUserLevelCas.changeEvent(function (value, node) {
        console.log('级别的变化', value)
    })
    let priceUserTypeCas = layui.layCascader({
        elem: `#userType`,
        clearable: true, // 显示清除按钮
        // options:data,
        props: {
            multiple: true, // 允许多选
            // strictMode:true//开启严格模式
        },
        // value:selectedData
    })
    priceUserTypeCas.changeEvent(function (value, node) {
        console.log('类型的变化：', value, node)
    })
    let priceSpeUserCas = layui.layCascader({//单选
        elem: `#speUser`,
        clearable: true, // 显示清除按钮
        props: {
            multiple: true, // 允许多选
            // strictMode:true//开启严格模式
        },
    })
    priceSpeUserCas.changeEvent(function (value, node) {
        console.log('用户变化', node)
        console.log('priceSpeUserCas', priceSpeUserCas.getCheckedValues())
        // console.log('priceSpeUserCas.getCheckedNodes()', priceSpeUserCas.getCheckedNodes().map(item=>item.data))
    })
    // 申购规则表格实例
    const priceRuleTable = table.render({
        elem: '#priceRuleTable'
        , height: '.layui-tab-item'
        , data: []
        , page: true //开启分页
        , cols: [[ //表头
            { title: '序号', type: "numbers", width: 60, }
            , { field: 'systemBuyName', title: '规则名称' }
            , {
                field: 'systemBuyType', title: '规则类别', width: 150, templet:
                    function (d) {
                        return `<span>${ruleType[Number(d.systemBuyType)]}</span>`
                    }
            }
            , { field: 'userRule', title: '用户条件' }
            , { field: 'priceRule', title: '规则内容' }
            , { field: 'remark', title: '备注' }
            , { title: '操作', width: 200, toolbar: '#visibleBarRule' },
        ]]
    })

    /******************申购控制相关-事件处理******************/
    // 指定用户搜索功能
    $('.priceSearchUser').on('click', '.priceUserSearch', function () {
        const userName = form.val('userForm').searchUserName;
        console.log('userName', userName)
        // 使用示例
        userSearchReq(userName, priceSpeUsers)
            .then(function (result) {
                // 处理成功结果
                console.log(result);
                const { userArr, selectedData } = result;
                form.val('userForm', {
                    "searchUserName": null
                })
                priceSpeUserCasRender(userArr, selectedData)
            })

    })
    // 表格相关操作-编辑，查看详情，删除
    layui.table.on('tool(priceRuleTableFilter)', function (obj) {
        const data = obj.data;
        console.log('data', data)
        if (obj.event === 'edit') {
            const formPosition = $(".priceForm").offset().top;
            // 减少滚动距离，例如减少100像素
            const scrollPosition = formPosition - 100;
            // 使用animate方法滚动到表单元素的位置
            $("html, body").animate({
                scrollTop: scrollPosition
            }, 1000); // 1000表示滚动动画的持续时间（以毫秒为单位）
            // 取消禁用
            $("input").attr("disabled", false);
            $("input").css("background-color", '#fff');
            $('.layui-container .operate').css('display', 'flex')
            formValue(data)
            if (data.id === 0) {
                console.log('addOrEdit标识错误')
            }
            priceAddOrEdit = data.id;
        } else if (obj.event === 'detail') {
            const formPosition = $(".priceForm").offset().top;
            // 减少滚动距离，例如减少100像素
            const scrollPosition = formPosition - 100;
            // 使用animate方法滚动到表单元素的位置
            $("html, body").animate({
                scrollTop: scrollPosition
            }, 1000); // 1000表示滚动动画的持续时间（以毫秒为单位）
            formValue(data)
            // 禁用表单
            $("input").attr("disabled", true);
            $("input").css("background-color", '#e9ecef');
        } else if (obj.event === 'delete') {
            const id = obj.data.id;
            $.ajax({
                timeout: 30000,
                url: window.Http + "/system/buy/del/" + id,
                type: 'DELETE',
                headers: {
                    'Authorization': "Bearer " + sessionStorage.getItem('Token')
                },
                success: function (res) {
                    if (res.code === 200) {
                        layer.msg('删除成功')
                        priceRuleReq()
                    } else {
                        layer.msg(res.msg)
                    }
                }
            })
        }
    })
    // 监听密码生成方式
    form.on('select(encodeWay)', function (data) {
        if (data.value === 'random') {
            //   // 生成一个32位密码
            //   const randomPassword = generateRandomPassword(32);
            //   console.log('randomPassword',randomPassword,randomPassword.length,typeof randomPassword);
            //   form.val('securityForm',{
            //       "password":randomPassword
            //   })
            //   console.log(form.val("securityForm").password.length)
            // 使用jQuery禁用输入框
            $('input[name="password"]').attr('disabled', true);
        } else if (data.value === 'set') {
            $('input[name="password"]').attr('disabled', false);
            form.val('securityForm', {
                "password": ""
            })
            layer.msg('请输入密码)')
        }
    });
    // 新增规则
    $('.addPriceBtn').on('click', function () {
        // 取消禁用
        $("input").attr("disabled", false);
        $("input").css("background-color", '#fff');
        $('.layui-container .operate').css('display', 'flex')
        // 清空表单
        formValue()
        form.val('userForm', {
            searchUserName: null
        })
        // console.log('新增规则')
        const formPosition = $(".priceForm").offset().top;

        // 减少滚动距离，例如减少100像素
        const scrollPosition = formPosition - 100;
        // 使用animate方法滚动到表单元素的位置
        $("html, body").animate({
            scrollTop: scrollPosition
        }, 1000); // 1000表示滚动动画的持续时间（以毫秒为单位）
    })
    // 提交规则按钮 申购规则
    $('.submitBuyRule').on('click', function () {
        form.verify({
            minValue: function (value, item) {
                console.log('value', value)
                if (Number(value) < 0) {
                    return '最小值必须大于等于0';
                }
            },
            maxValue: function (value, item) {
                console.log('value', value)
                if (Number(value) < 0) {
                    return '最大值必须大于等于0';
                }
                // if (Number(value)<=Number(value)){
                //     return '最大值必须大于等于最小值';
                // }
            },
            minPrice: function (value, item) {
                if (Number(value) < 0) {
                    console.log('value', value)
                    return '最小值必须大于等于0';
                }
            },
            maxPrice: function (value, item) {
                if (Number(value) < 0) {
                    console.log('value', value)
                    return '最大值必须大于等于0';
                }
                // if (Number(value)<=Number(value)){
                //     console.log('value', value)
                //     return '最大值必须大于等于最小值';
                // }
            },
        });
        let verifyResult = form.validate('.priceForm')
        console.log('verifyResult', verifyResult)
        if (verifyResult) {
            // 表单数据
            const nameForm = form.val('nameForm')
            const userForm = form.val('userForm')
            // const buyForm=form.val('buyForm')
            const buyTimes = form.val('buyTimes')
            const buyDuring = form.val("buyDuring")
            const buyRecord = form.val("buyRecord")
            const buyList = [buyDuring, buyRecord, buyTimes]
            console.log('buy', buyList)
            const isCurrentBuyList = buyList.some((item) => {
                return (Number(item.minValue) < Number(item.maxValue)) && (Number(item.minPrice) < Number(item.maxPrice))
            })
            if (isCurrentBuyList) {
                const useTimes = selectWayConversion('useTimes', 'useTimesSelectway', 'selectway')
                const useDuring = selectWayConversion('useDuring', 'useDuringSelectway', 'selectway')
                const useSite = selectWayConversion('useSite', 'useSiteSelectway', 'selectway')
                const securityForm = form.val('securityForm')
                // 适应用户字段
                const userRuleAttribute = {
                    isVisible: userForm.isVisible,
                    mode: userForm.mode,
                    single: [
                        { type: 'userLevel', method: userForm.userLevelMethod, value: userForm.userLevelValue }
                    ],
                    collection: [
                        {
                            class: 'userType',
                            set: priceUserTypeCas.getCheckedValues()
                        }, {
                            class: "speUser",
                            set: priceSpeUserCas.getCheckedNodes().map(item => item.data)
                        }
                    ]
                }
                // 价格相关字段
                const priceRuleAttribute = {
                    isDiscuss: 0,
                    security: {},
                    use: {},
                    buy: {}
                }
                priceRuleAttribute.isDiscuss = form.val('isDiscuss').isDiscuss;
                priceRuleAttribute.security = stringToNumber(fillDataFromSecurityForm(securityForm))
                console.log('priceRuleAttribute.security', priceRuleAttribute.security)
                console.log('priceRuleAttribute.security json', JSON.stringify(priceRuleAttribute.security))
                priceRuleAttribute.buy = {
                    priceWay: 'new',
                    during: {
                        ...buyDuring,
                        tip: '访问期限'
                    },
                    times: {
                        ...buyTimes,
                        tip: '访问次数'
                    },
                    record: {
                        ...buyRecord,
                        tip: '按记录数访问'
                    }
                }
                for (let key in priceRuleAttribute.buy) {
                    stringToNumber(priceRuleAttribute.buy[key])
                }
                // console.log(' priceRuleAttribute.buy',  priceRuleAttribute.buy)
                priceRuleAttribute.use = {
                    priceWay: 'add',
                    during: {
                        ...useDuring,
                        tip: '使用期限'
                    },
                    times: {
                        ...useTimes,
                        tip: '使用次数'
                    },
                    site: {
                        ...useSite,
                        tip: '使用场景'
                    }
                }
                for (let key in priceRuleAttribute.use) {
                    stringToNumber(priceRuleAttribute.use[key])
                }
                // console.log('priceRuleAttribute.use', priceRuleAttribute.use)

                const productBuyRule = {
                    systemBuyName: nameForm.systemBuyName,
                    remark: nameForm.remark,
                    systemBuyType: nameForm.systemBuyType,
                    userRule: JSON.stringify(userRuleAttribute),
                    priceRule: JSON.stringify(priceRuleAttribute)
                }
                //     console.log('productBuyRule', productBuyRule)
                // console.log('productBuyRule.priceRule', productBuyRule.priceRule)
                // console.log('productBuyRule.userRule', productBuyRule.userRule)
                if (priceAddOrEdit === 0) {
                    $.ajax({
                        timeout: 30000,
                        url: window.Http + "/system/buy/create",
                        type: 'POST',
                        headers: {
                            'Authorization': "Bearer " + sessionStorage.getItem('Token')
                        },
                        contentType: "application/json",
                        data: JSON.stringify(productBuyRule),
                        success: function (res) {
                            if (res.code === 200) {
                                console.log('productBuyRule', productBuyRule)
                                console.log('res', res)
                                layer.msg('新增规则成功')
                                priceRuleReq()
                                formValue()
                                form.val('userForm', {
                                    searchUserName: null
                                })
                            } else {
                                layer.msg(res.msg)
                            }
                        }
                    })
                } else {
                    productBuyRule.id = priceAddOrEdit;
                    $.ajax({
                        timeout: 30000,
                        url: window.Http + "/system/buy/update",
                        type: 'PUT',
                        headers: {
                            'Authorization': "Bearer " + sessionStorage.getItem('Token')
                        },
                        contentType: "application/json",
                        data: JSON.stringify(productBuyRule),
                        success: function (res) {
                            if (res.code === 200) {
                                console.log('productBuyRule', productBuyRule)
                                console.log('res', res)
                                layer.msg('修改规则成功')
                                priceAddOrEdit = 0
                                priceRuleReq()
                                formValue()
                                form.val('userForm', {
                                    searchUserName: null
                                })
                            } else {
                                layer.msg(res.msg)
                            }
                        }
                    })
                }
            } else {
                layer.msg('请至少正确填写一种申购相关方式')
            }
        } else {
            console.log('验证没有通过')
        }
    })

    // 根据关键字搜索规则 搜索按钮
    $('.priceSearchBtn').on('click', function () {
        // 使用 jQuery 选择器选择输入框并获取其值
        const inputValue = $(".priceSearch input[name='keyword']").val();
        // 输出输入框的值
        console.log(inputValue);
        priceRuleReq(inputValue);
    })

    // 功能函数
    // 指定用户搜索请求
    function userSearchReq(userName, userArr) {
        return new Promise(function (resolve, reject) {
            $.ajax({
                timeout: 30000,
                url: window.Http + "/system/user/findSpeUser",
                type: 'GET',
                headers: {
                    'Authorization': "Bearer " + sessionStorage.getItem('Token')
                },
                data: {
                    userName: userName
                },
                success: function (res) {
                    if (res.code === 200) {
                        userArr.push({ value: res.data.userId, label: res.data.userName });
                        let selectedData = userArr.map(ele => Number(ele.value));
                        console.log('selectedData', selectedData);
                        console.log('userArr', userArr);
                        resolve({ userArr, selectedData });
                    } else {
                        layer.msg(res.msg);
                        reject("请求失败");
                    }
                }
            });
        });
    }
    // 可见指定用户select渲染
    function visibleSpeUserCasRender(data, selectedData) {
        visibleSpeUserCas.setOptions(data)
        visibleSpeUserCas.setValue(selectedData)
        console.log('data', data)
        console.log('selectedData', selectedData)
    }
    // 价格指定用户select渲染
    function priceSpeUserCasRender(data, selectedData) {

        // console.log('data', data,typeof data[0].value)
        // console.log('selectedData', selectedData,typeof selectedData[0])
        priceSpeUserCas.setOptions(data)
        priceSpeUserCas.setValue(selectedData.map(item => Number(item)))
        // priceSpeUserCas.setValue([1])
    }
    // 申购规则请求
    function priceRuleReq(keyword = null) {
        // 价格控制规则列表请求
        $.ajax({
            timeout: 30000,
            url: window.Http + "/system/buy/list",
            type: 'GET',
            headers: {
                'Authorization': "Bearer " + sessionStorage.getItem('Token')
            },
            data: { keyword },
            success: function (res) {
                if (res.code === 200) {
                    // console.log('res', res)
                    priceRuleTable.reload({ data: res.rows || [] })
                }
            }
        })
    }
    priceRuleReq()
    // 可见规则请求
    function visibleRuleReq(keyword = null) {
        $.ajax({
            timeout: 30000,
            url: window.Http + "/system/control/list",
            type: 'GET',
            headers: {
                'Authorization': "Bearer " + sessionStorage.getItem('Token')
            },
            data: {
                keyword
            },
            success: function (res) {
                if (res.code === 200) {
                    visibleRuleTable.reload({ data: res.rows })
                } else {
                    layer.msg('获取可见规则失败')
                }
            }
        })
    }
    visibleRuleReq()
    // 把表单对象转成对应格式 -安全相关
    function fillDataFromSecurityForm(securityForm) {
        let targetObj = {}
        targetObj.priceWay = 'add';
        targetObj.confirm = {
            select: securityForm.confirmSelect,
            price: securityForm.confirmPrice
        };
        targetObj.auth = {
            select: securityForm.authSelect,
            price: securityForm.authPrice
        };
        targetObj.encrypt = {
            encode: {
                select: securityForm.encodeSelect,
                price: securityForm.encodePrice
            },
            way: {
                select: securityForm.encodeWay,
                password: CryptoJS.SHA256(securityForm.password).toString(CryptoJS.enc.Hex).slice(0, 32)
            },
            place: {
                select: securityForm.codePlace
            }
        };
        console.log('password', targetObj.encrypt.way.password)
        console.log('length', targetObj.encrypt.way.password.length)
        return targetObj;
    }
    // 把数据转成对应表单格式-安全相关
    function fillSecurityFormFromData(data) {
        return {
            "confirmSelect": data.confirm.select,
            "confirmPrice": data.confirm.price,
            "authSelect": data.auth.select,
            "authPrice": data.auth.price,
            "encodeSelect": data.encrypt.encode.select,
            "encodePrice": data.encrypt.encode.price,
            "encodeWay": data.encrypt.way.select || 'set',
            "codePlace": data.encrypt.place.select || 'platform',
            // "password":data.encrypt.way.password
        };
    }
    // 申购相关表单赋值
    function formValue(data) {
        let userRule = null;
        let priceRule = null;
        const resetForm = {
            "minValue": null,
            "maxValue": null,
            "minPrice": null,
            "maxPrice": null,
            "calcway": "average",
        }
        if (!data) {
            form.val('nameForm', {
                "systemBuyName": null,
                "systemBuyType": null,
                "remark": null
            })
            // 是否允许议价
            form.val('isDiscuss', {
                "isDiscuss": 0
            })
            form.val('userForm', {
                "mode": 1,
                "userLevelMethod": 0,
                "userLevelValue": 0,
                "isVisible": 0,
                "searchUserName": null
            })
            priceUserLevelCas.setValue(0)
            priceUserTypeCas.setValue([])
            priceSpeUserCas.setValue([])
            // 价格相关表单赋值
            form.val('useDuring', {
                ...resetForm,
                "useDuringSelectway": 0
            })
            form.val('useTimes', {
                ...resetForm,
                "useTimesSelectway": 0
            })
            form.val('useSite', {
                ...resetForm,
                "useSiteSelectway": 0
            })
            form.val('buyDuring', resetForm)
            form.val('buyTimes', resetForm)
            form.val('buyRecord', resetForm)
            form.val('securityForm', {
                "confirmSelect": 0,
                "confirmPrice": null,
                "authSelect": 0,
                "authPrice": null,
                "encodeSelect": 0,
                "encodePrice": null,
                "codePlace": "platform",
                "encodeWay": "random",
                "password": ""
            })
        } else {
            userRule = JSON.parse(data.userRule)
            console.log('form userRule', userRule)
            priceRule = JSON.parse(data.priceRule)
            // 名字表单赋值
            form.val('nameForm', {
                "systemBuyName": data.systemBuyName,
                "systemBuyType": data.systemBuyType,
                "remark": data.remark
            })
            // 适应用户表单赋值
            form.val('userForm', convertToUserForm(userRule))
            // 价格相关表单赋值
            form.val('useDuring', {
                ...priceRule.use.during,
                'useDuringSelectway': priceRule.use.during.selectway
            })
            form.val('useTimes', {
                ...priceRule.use.times,
                'useTimesSelectway': priceRule.use.times.selectway
            })
            form.val('useSite', {
                ...priceRule.use.site,
                "useSiteSelectway": priceRule.use.site.selectway
            })
            form.val('buyDuring', priceRule.buy.during)
            form.val('buyTimes', priceRule.buy.times)
            form.val('buyRecord', priceRule.buy.record)
            form.val('securityForm', fillSecurityFormFromData(priceRule.security))
            // 是否允许议价
            form.val('isDiscuss', {
                "isDiscuss": priceRule.isDiscuss
            })
        }

    }
    // 可见的表单赋值
    function visibleFormValue(data) {
        let single = null;
        let collection = null
        if (!data) {
            form.val('visibleNameForm', {
                "systemControlName": null,
                "visibleRuleRemark": null
            })
            form.val('visibleForm', {
                "mode": 1,
                "userLevelMethod": 0,
                "userLevelValue": 0,
                "isVisible": 0
            })
            visibleUserLevelCas.setValue(0)
            visibleUserTypeCas.setValue([]);
            visibleSpeUserCas.setValue([]);
        } else {
            single = JSON.parse(data.single);
            collection = JSON.parse(data.collection)
            form.val('visibleNameForm', {
                "systemControlName": data.systemControlName || null,
                "remark": data.remark || null
            })
            form.val('visibleForm', {
                "mode": data.ruleMode || 1,
                "userLevelMethod": single[0].method || 0,
                "userLevelValue": single[0].value || 0,
                "isVisible": data.isVisible
            })
            // const userTypeSet = collection.find(item => item.class === 'userType').set;
            // const speUserSet = collection.find(item => item.class === 'speUser').set;
            if (data.speUserTypeList && data.speUserTypeList.length) {
                const typeIds = data.speUserTypeList.map(item => item.toString())
                visibleUserTypeCas.setValue(typeIds);
            }
            if (data.speUserList && data.speUserList.length > 0) {
                visibleSpeUserCas.setOptions(dataFormat(data.speUserList, 'speUserId', 'speUserName'))
                const speUserIds = data.speUserList.map(item => item.speUserId)
                visibleSpeUserCas.setValue(speUserIds);
            }
            if (single && single.length > 0) {
                visibleUserLevelCas.setValue(single[0].value)
            }
        }

    }
    // 把数据转成表单格式-适应用户
    function convertToUserForm(userRuleAttribute) {
        const userForm = {
            "isVisible": userRuleAttribute.isVisible,
            "mode": userRuleAttribute.mode,
            "userLevelMethod": userRuleAttribute.single.find(cond => cond.type === 'userLevel').method,
            "userLevelValue": userRuleAttribute.single.find(cond => cond.type === 'userLevel').value
        };
        const userLevelValue = userRuleAttribute.single.find(cond => cond.type === 'userLevel').value
        const userTypeSet = userRuleAttribute.collection.find(item => item.class === 'userType').set;
        const speUserSet = userRuleAttribute.collection.find(item => item.class === 'speUser').set;

        priceUserTypeCas.setValue(userTypeSet);
        priceSpeUserCasRender(speUserSet, speUserSet.map(item => item.value))
        priceSpeUserCas.setValue(speUserSet);
        priceUserLevelCas.setValue(userLevelValue)
        return userForm;
    }
    // 把表单转成提交数据格式-适应用户
    function convertToUserRuleAttribute(userForm) {
        return {
            isVisible: userForm.isVisible,
            mode: userForm.mode,
            single: [
                { type: 'userLevel', method: userForm.userLevelMethod, value: userForm.userLevelValue }
            ],
            collection: [
                {
                    class: 'userType',
                    set: priceUserTypeCas.getCheckedValues()
                },
                {
                    class: 'speUser',
                    set: priceSpeUserCas.getCheckedValues()
                }
            ]
        };
    }
    // 数据转换成级联列表需要的样式
    // data:原始数组，value:绑定的值（id），label：标签显示值，返回正确格式数组
    function dataFormat(data, value, label) {
        let arr = []
        data.forEach(function (item, index) {
            arr[index] = { value: '', label: '' }
            arr[index].value = data[index][value];
            arr[index].label = data[index][label]
        })
        return arr;
    }
    //formName表单名字，curSelWayName，现在的selectway名字，targetSelWayName目前selectway名字
    function selectWayConversion(formName, curSelWayName, targetSelWayName) {
        const formData = form.val(formName)
        formData[targetSelWayName] = formData[curSelWayName];
        delete formData[curSelWayName];
        return formData
    }

    /**字符串转数字类型函数
     *
     * @param obj 传入的对象
     * 把对象的 minValue maxValue maxPrice minPrice price从字符串转为对象
     */
    function stringToNumber(obj) {
        for (let key in obj) {
            switch (key) {
                case 'minValue':
                    obj.minValue = Number(obj.minValue)
                    break;
                case 'maxValue':
                    obj.maxValue = Number(obj.maxValue)
                    break;
                case 'maxPrice':
                    obj.maxPrice = Number(obj.maxPrice)
                    break;
                case 'minPrice':
                    obj.minPrice = Number(obj.minPrice)
                    break;
                case 'price':
                    obj.price = Number(obj.price)
                    break;
                default:
                    break;
            }
        }
        return obj;
    }
    /**
     * @description:函数描述 随机产生密码 16位
     * @return string
     * @param length {Number} 密码长度
     */
    function generateRandomPassword(length) {
        const charset = "ABCDEF0123456789";
        let password = "";
        const charsetLength = charset.length;

        if (window.crypto) {
            const randomValues = new Uint32Array(length);
            window.crypto.getRandomValues(randomValues);

            for (let i = 0; i < length; i++) {
                const randomIndex = randomValues[i] % charsetLength;
                password += charset.charAt(randomIndex);
            }
        } else {
            console.error("Crypto API not available. Falling back to Math.random().");
            for (let i = 0; i < length; i++) {
                const randomIndex = Math.floor(Math.random() * charsetLength);
                password += charset.charAt(randomIndex);
            }
        }

        return password;
    }
    // 监听申购规则类型
    form.on('select(systemBuyType)', function (data) {
        if (data.value === '2') {
            $('.dataProductRule').addClass('disabledNone');
            $('.serviceProductRule').removeClass('disabledNone');
        } else {
            $('.dataProductRule').removeClass('disabledNone');
            $('.serviceProductRule').addClass('disabledNone');
        }
    });

})
